package com.fyzk.activity.news;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.net.Commands;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import com.wf.domain.UrlDef;

/**
 * Created by miao on 2017/5/19.
 */
@ContentView(R.layout.ac_news)
public class NewsActivity extends BaseActivity {
    private List<Fragment> mFragments;
    @ViewInject(R.id.newsUI_tabLayout)
    private TabLayout mTabLayout;
    @ViewInject(R.id.newsUI_viewPager)
    private ViewPager mViewPager;
    @ViewInject(R.id.newsUI_topView)
    private TopTitleView mTopView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        httpNewsType();
        initListener();
    }

    /**
     * 获取新闻类型列表
     */
    protected void httpNewsType() {
        RequestParams params = new RequestParams(UrlDef.NEWS_URL+ Commands.NEWSTYPELIST);
        params.addBodyParameter("category", "blog");
        sendRequestGet(HttpMethod.GET, 0, params, true);
    }

    @Override
    protected void onSuccess(int requestCode, String result) {
        super.onSuccess(requestCode, result);

        NewsTypeListBean newsTypeList = JSON.parseObject(result, NewsTypeListBean.class);
        int code = newsTypeList.getCode();

        if (code > 0) {
            List<NewsTypeListBean.CategoryBean> newsTypeBeans = newsTypeList.getData();
            mFragments = new ArrayList<>();
            String[] titles = new String[newsTypeBeans.size()];
            for (int i=0;i<newsTypeBeans.size();i++){
                NewsTabFragment fragment = new NewsTabFragment().newInstance(newsTypeBeans.get(i));
                mFragments.add(fragment);
                titles[i] = newsTypeBeans.get(i).getName();
            }
            BaseFragmentAdapter adapter = new BaseFragmentAdapter(getSupportFragmentManager(), mFragments, titles);
            mViewPager.setAdapter(adapter);
            mTabLayout.setupWithViewPager(mViewPager);
            mViewPager.setOffscreenPageLimit(newsTypeBeans.size());
            mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        }else{
            AppToast.getToast().show(newsTypeList.getMsg());
        }

    }

    private void initListener() {
        mTopView.setOnTitleClickListener(this);
    }

}
